import { OAuth2Client, TokenPayload } from 'google-auth-library';
import { publicKeysString } from '../assets/google-publickeys';
import jwt from 'jsonwebtoken';
import { app } from '..';
import { Prisma, User } from '@prisma/client';
import { z } from 'zod';
import userTokenService from './userToken.service';


class UserService {
    createUserSchema = z.object({
        email: z.string().email(),
        password: z.string().min(6),
    });

    async query(where: Partial<User>) {
        return await app.prisma.user.findFirst({ where });
    }

    async get() {
        return await app.prisma.user.findMany();
    }

    async create(user: typeof this.createUserSchema._type) {
        if (await this.query({ email: user.email })) {
            throw new Error('user already exists');
        }

        try {
            return await app.prisma.$transaction(async (tx) => {
                const retUser = await tx.user.create({ data: user }) as User;
                const userToken = await tx.userToken.create({ data: { token: userTokenService.generate(retUser), userId: retUser.id } });
                return {
                    ...retUser,
                    apiToken: userToken.token,
                };
            });
        } catch (e) {
            throw new Error('create user error');
        } finally {
            await app.prisma.$disconnect();
        }
    }

    // 是否是付费用户
    async isPayingUser(user: User) {
        const userSubscription = await app.prisma.userSubscription.findFirst({
            where: {
                userId: user.id,
                endDate: { gte: new Date() }
            }
        });
        return !!userSubscription;
    }

    // 是否是免费用户
    async isFree(user: User) {
        return !(await this.isPayingUser(user));
    }
}

export default new UserService();